package be.vdab.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

@Repository("namenDAOXML")
@Qualifier("XMLFormaat")
public class NamenDAOXML implements NamenDAO {
	private File bestand;
	
	@Autowired
	public NamenDAOXML(@Value("${namenXML}")File bestand) {
	this.bestand = bestand;
	System.out.println("constructor " + this.getClass().getName());
	}

	public void setBestand(File bestand) {
		this.bestand = bestand;
	}

	@Override
	public void opslaan(Collection<String> namen) {
		PrintStream stream = null;
		try {
			stream = new PrintStream(bestand, "UTF-8");
			stream.println("<namen>");
			for (String naam : namen) {
				stream.println("\t<naam>" + naam + "</naam>"); // \t = tab teken
			}
			stream.println("</namen>");
		} catch (IOException ex) {
			throw new NamenDAOException(ex);
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	@Override
	public int getAantalOpgeslagenNamen() {
		if (!bestand.exists()) {
			return 0;
		}
		BufferedReader reader = null;
		try {
			int aantalNamen = 0;
			reader = new BufferedReader(new FileReader(bestand));
			for (String regel; (regel = reader.readLine()) != null;) {
				if (regel.contains("<naam>")) {
					aantalNamen++;
				}
			}
			return aantalNamen;
		} catch (IOException ex) {
			throw new NamenDAOException(ex);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
